﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using MIXer.Core.Contracts;
using MIXer.Core.Domain;
using MIXer.Core.Extensions;

namespace MIXer.Providers
{
    [Export(typeof(INameTransformer))]
    public class SessionNameTransformer : INameTransformer
    {
        #region Inner Classes
        class NameToken
        {
            public string Token { get; set; }
            public Func<string, Session, string> Transform { get; set; }
        }
        #endregion

        #region Constants
        private static readonly string[] IllegalChars = new string[] { "?", ":", "*", ">", "<", "\"", "\\", "/", "|" };
        #endregion

        #region Fields
        private List<NameToken> _tokens;
        #endregion

        #region Constructors
        public SessionNameTransformer()
        {
            _tokens = new List<NameToken> 
            {
                new NameToken { Token = "$title", Transform = (input, session) => input.Replace("$title", session.Title).RemoveIllegalChars(IllegalChars) },
                new NameToken { Token = "$event", Transform = (input, session) => input.Replace("$event", session.EventCode).RemoveIllegalChars(IllegalChars) },
                new NameToken { Token = "$code", Transform = (input, session) => input.Replace("$code", session.SessionCode).RemoveIllegalChars(IllegalChars) }
            };
        }
        #endregion

        #region Methods
        public string Transform(string input, Session session)
        {
            if(String.IsNullOrEmpty(input))
                return input;

            foreach (var token in _tokens)
            {
                input = token.Transform(input, session);
            }

            return input;
        }
        #endregion

        #region Properties
        public string[] AvailableTokens
        {
            get
            {
                return _tokens.Select(x => x.Token).ToArray();
            }
        }
        #endregion
    }
}
